package com.meisiabc.support.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class EmailClient {
    private JavaMailSender mailSender;

    public EmailClient(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void send(String from, String to, String subject, String htmlText) {
        send(from, to, null, subject, htmlText);
    }

    public void send(String from, String to, String[] cc, String subject, String htmlText) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);

            InternetAddress[] internetAddresses = toInternetAddress(cc);
            if (internetAddresses.length > 0) {
                message.addRecipients(Message.RecipientType.CC, internetAddresses);
            }

            helper.setSubject(subject);
            helper.setText(htmlText, true);
            mailSender.send(message);
            log.info("from[{}] to[{}] cc[{}] subject[{}] htmlText[{}] send success.", from, to, cc, subject, htmlText);
        } catch (MessagingException e) {
            log.error("from[{}] to[{}] cc[{}] subject[{}] htmlText[{}] send error.", from, to, cc, subject, htmlText);
        }
    }

    private InternetAddress[] toInternetAddress(String[] cc) {
        if (cc == null) {
            return new InternetAddress[]{};
        }

        List<InternetAddress> internetAddressList = new ArrayList<>();
        for (int i = 0; i < cc.length; i++) {
            try {
                String ccAddr = cc[i];
                if (StringUtils.isEmpty(ccAddr)) {
                    continue;
                }
                internetAddressList.add(new InternetAddress(ccAddr));
            } catch (AddressException e) {
                log.error("toInternetAddress error. cc:{}", cc, e);
            }
        }

        return internetAddressList.toArray(new InternetAddress[internetAddressList.size()]);
    }
}
